<template>
<div class="login">
  <el-form
      v-loading="loading"
      element-loading-text="正在登录..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :rules="rules"
      :model="loginForm"
      ref="form"
      class="login-tag" @keydown.enter.native="loginAccount">
    <h2 style="margin: 0 auto 30px auto;text-align: center">系统登录</h2>
    <el-form-item prop="username">
      <el-input type="text" placeholder="请输入用户名" v-model="loginForm.username"/>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" placeholder="请输入密码" v-model="loginForm.password"/>
    </el-form-item>
    <el-form-item prop="code">
      <el-input type="text" placeholder="点击图片获取验证码" v-model="loginForm.code" style="width: 220px"/>
      <img :src="captchaUrl" @click="captchaClick" style="margin-left: 5px; vertical-align:middle;" alt="">
    </el-form-item>
    <el-checkbox :model="checked">记住我</el-checkbox>
    <el-button type="primary" style="width: 100%;margin-top: 20px"
               @click="loginAccount">登录</el-button>
  </el-form>
</div>
</template>

<script>

export default {
name: "login",
  data(){
  return{
    loginForm:{
   username:'',
   password:'',
   code: null
   },
    checked:true,
    loading: false,
    //掉验证码图片接口
    captchaUrl:'/captcha?time='+new Date(),
    rules:{
      userName:[{required:true,message: '请输入账号',trigger: 'blur'}],
      password: [{required:true,message: '请输入密码',trigger: 'blur'}],
      code: [{required:true,message: '请输入验证码',trigger: 'blur'}]
    }
  }
  },
  methods:{
  loginAccount(){//登录
    this.$refs.form.validate((valid) => {
      if (valid) {
        this.loading = true
        this.postRequest('/login',this.loginForm).then(res=>{
          if(res){
            this.loading = false
            //登录之后拿到token
            const tokenStr = res.obj.tokenHead + res.obj.token
            //把token保存到本地缓存(注意：不要愚蠢得想用等号去赋值，用setItem)
            window.sessionStorage.setItem('tokenStr',tokenStr)
            //跳转页面
            //之前退出来的页面
            let path = this.$route.query.redirect
            this.$router.replace((path === '/' || path === undefined)?'/home':path)
          }
        })

      } else {
       this.$message.error('请输入内容')
        return false;
      }
  })
  },
   /* enterAccount(){
      if (keyCode === 13) {
        this.loginAccount()
      }

    },*/
    captchaClick(){//点击更换图片
    this.captchaUrl = '/captcha?time='+new Date()
    }
}
}
</script>

<style scoped>
.login-tag{
  border-radius: 15px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 15px 35px 15px 35px;
  background: #ffff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}
.el-form-item__content{
  display: flex;
  align-items: center;
}
</style>